package sip.oshima.ua.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class DelayedTaskCancellationExample {
    private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    private static ScheduledFuture<?> currentTask;

    public static void main(String[] args) {
        // 启动第一个延时任务
        addDelayedTask(() -> System.out.println("第一个任务执行"));

        try {
            // 模拟等待一段时间后添加新任务
            Thread.sleep(3000);
            addDelayedTask(() -> System.out.println("第二个任务执行"));

            System.out.println("主线程等待");
            while (true){

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }
    }

    /**
     * 添加延时两分钟执行的任务，添加前取消之前的任务
     * @param task 要执行的任务
     */
    public static void addDelayedTask(Runnable task) {
        // 取消当前正在等待执行的任务
        if (currentTask != null) {
            currentTask.cancel(false);
        }
        // 安排新的延时任务，延时两分钟（120000 毫秒）执行
        currentTask = executorService.schedule(task, 5, TimeUnit.SECONDS);
    }
}